package com.deneme;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class DeleteImage extends HttpServlet {
    private static BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
	
	public void doGet(HttpServletRequest req,
			HttpServletResponse resp)
					throws IOException {
    	doPost(req, resp);
    }
    
    public void doPost(HttpServletRequest req,
			HttpServletResponse resp)
					throws IOException {
    	
    	// Get the User Data
    	UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		UserData userData = UserData.getDataForUser(user);
		
		// Get the blob-key to delete, as well as the user's puzzles.
		// We have to delete any saved puzzle using this image, or we will be unable to load that puzzle
		String incomingKey = req.getParameter("blob-key");
		BlobKey blobKey = new BlobKey(incomingKey);
		ArrayList<String> puzzKeys = userData.getPuzzleKeys();
		
		// Remove the iamge from the user's list
		ArrayList<BlobKey> imgKeys = userData.getImageKeys();
		imgKeys.remove(blobKey);
		userData.setImageKeys(imgKeys);

		// Loop through the user's puzzles, and remove any that contain the image we are deleting
		for (int i = 0; i < puzzKeys.size(); ++i) {
			String key = puzzKeys.get(i);
			SavedPuzzle puzzle = SavedPuzzle.getPuzzleForKey(key);
			if (puzzle != null && blobKey.equals(puzzle.getImgKey())) {
				puzzKeys.remove(key);
				puzzle.delete();
				--i;
				continue;
			}
		}
		// Update the user's arrays and save the new data
		userData.setPuzzleKeys(puzzKeys);
		userData.save();

		// Finally, delete the image from the blobstore
		blobstoreService.delete(blobKey);
		
		// Forward back to view images
		RequestDispatcher rd = req.getRequestDispatcher("/viewimages");
		try {
			rd.forward(req, resp);
		} catch (ServletException e) {
			e.printStackTrace();
		}
		
	}
}
